package librus.codebase.image;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageProcessor 
{
	//DX - 824 x 1200

	public BufferedImage resize(BufferedImage image, int width, int height) 
	{
		BufferedImage resizedImage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		g.dispose();
		return resizedImage;
	}

	public BufferedImage rotate90(BufferedImage image) 
	{
		int width = image.getWidth();
		int height = image.getHeight();
		
		BufferedImage biFlip = new BufferedImage(height, width, image.getType());
		
		for(int i=0; i<width; i++)
			for(int j=0; j<height; j++)
				biFlip.setRGB(j, width-1-i, image.getRGB(i, j));
		
		return biFlip;
	}
	
	public WideImage slice(BufferedImage image)
	{
		int width = image.getWidth();
		int height = image.getHeight();
		
		int halfWidth = Math.round((float)width/2)-1;
		
		WideImage result = new WideImage(halfWidth, height);
		
		int[] pixels = new int[halfWidth * height];
		
		image.getRGB(0, 0, halfWidth, height, pixels, 0, halfWidth);
		result.left.setRGB(0, 0, halfWidth, height, pixels, 0, halfWidth);
		
		image.getRGB(halfWidth, 0,halfWidth,height,pixels,0,halfWidth);
		result.right.setRGB(0, 0, halfWidth, height, pixels, 0, halfWidth);
						
		return result;
	}
	
	public BufferedImage quantize(BufferedImage image) 
	{
		int width = image.getWidth();
		int height = image.getHeight();
		
		int[] pixels = new int[width * height];
		image.getRGB(0, 0, width, height, pixels, 0, width); // Get all pixels
		
		for (int i = 0; i < pixels.length; i++)
			pixels[i] = ((Math.round(pixels[i] / 0x111111)) * 0x111111) - 1;
		image.setRGB(0, 0, width, height, pixels, 0, width);
		
		return image;
	}
	
	public void saveImage(BufferedImage image, String path) throws IOException 
	{		
		path += ".png";			
		File out = new File(path);
		ImageIO.write(image, "png", out);
	}

}
